package br.com.escolaespacocrianca.fineec.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Validations;
import br.com.caelum.vraptor.view.Results;
import br.com.escolaespacocrianca.fineec.business.GroupBusiness;
import br.com.escolaespacocrianca.fineec.business.SponsorBusiness;
import br.com.escolaespacocrianca.fineec.component.Resources;
import br.com.escolaespacocrianca.fineec.model.Group;

@Resource
public class GroupController {

	private Validator validator;
	private final Result result;
	private final GroupBusiness business;

	public GroupController(Result result, Validator validator, HttpServletRequest request, GroupBusiness business,SponsorBusiness businessSponsor) {
		this.result = result;
		this.business = business;
		this.validator = validator;
	}
 
	@Get("/group")
	public void index() {
		result.forwardTo(SharedController.class).index("group","Grupo");
	}
	
	public List<Group> list() {

		return business.list();
	}
	
	
	public Group maintain(Group group) {
		
		Group groupFull = null;
		if (group != null && group.getId() != null){
			groupFull = business.find(group.getId());
		}
		return groupFull;
	}

	public void delete(Group group) {

		business.delete(group);

		result.use(Results.json()).withoutRoot().from(Resources.getMessage("group.delete.success")).serialize();
	}

	
	public void save(final Group group,final String checkPassword) {
		
		validator.checking(new Validations(){{
			that(!group.getDescription().isEmpty(), "validation","group.description.empty");
	    }});  
	    	
		validator.onErrorSendBadRequest();
		
		business.saveOrUpdate(group);
		
		result.use(Results.json()).withoutRoot().from(Resources.getMessage("group.save.success")).serialize();
	}
}
